from wordcloud import WordCloud
import PIL.Image as image
import jieba
from utils import open_txt
import matplotlib.pyplot as plt
import numpy as np


# 词云
class MyWordCloud():
    def __init__(self, txt_path, mask_path, save_path):
        '''
        :param txt_path: 要做成词云的文字信息
        :param mask_path: 词云形状mask，背景色为白色
        :param save_path: 保存词云图片的路径
        '''
        self.txt_path = txt_path
        self.mask_path = mask_path
        self.save_path = save_path

    # 结巴分词
    def cut(self, text):
        word_list = jieba.cut(text,cut_all= False) # 选择分词模式
        result = " ".join(word_list) # 分词后在单独个体之间加上空格
        return result

    # 生成词云
    def __call__(self):
        mytext = open_txt(self.txt_path)

        # 结巴分词
        mytext = self.cut(mytext)

        # 定义词云形状，https://blog.csdn.net/wulishinian/article/details/105201898
        mask = np.array(image.open(self.mask_path))

        # 生成词云，清晰度：https://blog.csdn.net/dingpangxie3730/article/details/101894453
        wordcloud = WordCloud(
            mask=mask,
            background_color='#FFFFFF',  # 背景设置为白色
            scale=32,
        ).generate(mytext)

        # 显示与保存
        # plt.imshow(wordcloud, interpolation='bilinear') # nearest
        plt.axis("off")
        wordcloud.to_file(self.save_path)